package com.gupt.reggie.service.impl;/*
@author name
@data 2023/4/19-18:00
*/


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gupt.reggie.common.CustomException;
import com.gupt.reggie.dto.SetmealDto;
import com.gupt.reggie.entity.Category;
import com.gupt.reggie.entity.Setmeal;
import com.gupt.reggie.entity.SetmealDish;
import com.gupt.reggie.mapper.SetmealMapper;
import com.gupt.reggie.service.CategoryService;
import com.gupt.reggie.service.SetmealDishService;
import com.gupt.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    SetmealDishService setmealDishService;
    @Autowired
    @Lazy
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void saveWithDish(SetmealDto setmealDto) {

        //新增套餐 保存套餐和菜品的关联关系
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item) ->{
            item.setSetmealId(setmealDto.getId());  //getID 为 setmealId
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);  //批量保存

//        //精确清理某一个类型的缓存数据
//        String key = "setmeal_" + setmealDto.getCategoryId() + "_1";
//        redisTemplate.delete(key);
    }


    //删除套餐，同时删除套餐与菜品关联的数据
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
    //只能删除停售的套餐
    //sql:   select count(*) from setmeal where id in (1,2,3) and status = 1; 1:售卖中
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);

        int count = this.count(queryWrapper);
        if(count > 0){
            //无法删除，则抛出异常
            throw new CustomException("套餐正在售卖，不能删除");
        }
        //删除套餐表的记录
        this.removeByIds(ids);  // s:批量删除

        //删除关联表记录 setmeal_dish
//      delete from setmeal_dish where setmeal_id in (1,2,3);
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(wrapper);
    }

    @Override
    public SetmealDto getByIdWithFlavor(Long id) {
        //查询套餐基本信息
        Setmeal setmeal = this.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        //套餐信息对象赋值给套餐dto
        BeanUtils.copyProperties(setmeal,setmealDto);
        //查询套餐具体菜品信息
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(queryWrapper);
        //手动set菜品信息  菜品名称 套餐id
        setmealDto.setSetmealDishes(list);
        return setmealDto;
    }

    @Override
    public void updateWithDish(SetmealDto setmealDto) {
        //修改该套餐基本数据
        this.updateById(setmealDto);
        //删除当前所有菜品数据
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(queryWrapper);

        // 添加新的套餐菜品表单数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream()
                .filter(item -> item.getName() != "")
                .peek(item -> item.setSetmealId(setmealDto.getId()))
                .collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

//        //精确清理某一个类型的缓存数据
//        String key = "setmeal_" + setmealDto.getCategoryId() + "_1";
//        redisTemplate.delete(key);
    }

    @Override
    public Page page(int page, int pageSize, String name) {
        //新建分页构造器
        Page<Setmeal> pageInfo = new Page(page, pageSize);
        Page<SetmealDto> dtoPage = new Page();

        //条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Setmeal::getName, name);
        //排序
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        pageInfo = this.page(pageInfo, queryWrapper);

        //对象拷贝
        //records:为当前查询信息记录 不拷贝，why Page类泛型不一致
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<Setmeal> records = pageInfo.getRecords();
        //将 records中的查询信息赋值给list
        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝  将套餐的普通信息赋值给dto----------------------------------
            BeanUtils.copyProperties(item, setmealDto);
            Long categoryId = item.getCategoryId();

            //根据分类id查询分类信息
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                //将类型名赋值进去--------------------------------
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);

        return dtoPage;
    }
}
